<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-button :loading="exportLoading" class="item-gap" size="mini" type="warning" @click="onReportBtn">导出</el-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" clearable placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size2 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-select v-model="searchParams.processCode" clearable placeholder="工序" value-key-name="code" :option-list="processList" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-date-picker v-model="searchParams.belongDates" type="daterange" :clearable="false" placeholder="日期" :picker-options="pickerOptions" size="small" class="search-bar-item-size4 margin-5-0 item-gap"></jk-date-picker>
					<!--<jk-select v-model="searchParams.shiftId" clearable placeholder="班次" :option-list="shiftList" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
					<jk-select v-model="searchParams.groupId" clearable placeholder="班组" :option-list="groupList" size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.machineName" placeholder="机台名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.yarnCount" placeholder="支数" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.empName" placeholder="值车工" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" border :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatDate } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        productionPrdReportEmployeeOutputList,
        productionPrdReportEmployeeOutputPage
    } from '../../../api/production/reports';
    import { workforcemanagementShiftPage } from '../../../api/schedule/shift';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import filterProcessList from '../../../mixins/filter-process-list';

    export default {
        name: 'DailyReport',
        mixins: [calHeight, getMenuColumn, handlerCache, filterProcessList],
        data() {
            return {
                apiItem: {
                    'page': productionPrdReportEmployeeOutputPage,
                    'report': productionPrdReportEmployeeOutputList
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                exportLoading: false,
                processList: [],
                workshopList: [],
                tableLoading: true,
                tableData: [],
                totalCount: 0,
                shiftList: [],
                groupList: [],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    belongDates: [],
                    shiftId: null,
                    groupId: null,
                    processCode: '',
                    workshopId: null,
                    yarnCount: '',
                    machineName: ''
                }
            };
        },
        mounted() {
            if (!this.searchParams.processCode) {
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
            }
            if (!this.searchParams.workshopId) {
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            this.getDependentData();
        },
        methods: {
            /** 导出按钮操作 */
            onReportBtn() {
                const headers = this.$refs.jkTable.$refs.xTable.getColumns() || [];
                const titles = headers.filter(x => x.title !== '操作').map(k => k.title);
                const keyNames = headers.filter(x => x.field !== 'operation').map(k => k.field);
                this.$modal.confirm('是否确认导出所有数据?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    const params = JSON.parse(JSON.stringify(this.searchParams));
                    // 查询条件加上导出参数标识，去掉分页条件以返回所有数据
                    params.ifExport = true;
                    delete params.pageNo;
                    delete params.pageSize;
                    return this.apiItem['report'](params).then(res => {
                        this.exportLoading = false;
                        if (res.data.status === 200) {
                            const list = res.data.res || [];
                            import('@/vendor/Export2Excel').then(excel => {
                                list.forEach(x => {
                                    x.gramWeight = `${x.gramWeight || ''}g/${x.meters || ''}m`;
                                });
                                const data = list.map(v => keyNames.map(j => {
                                    return v[j];
                                }));
                                // 合计项
                                // const cpData = JSON.parse(JSON.stringify(this.$refs.jkTable.$refs.xTable.getTableData().footerData[0]));
                                // data.push(cpData);
                                excel.export_json_to_excel({
                                    header: titles,
                                    data,
                                    filename: `${this.$route.meta.title || ''}`,
                                    autoWidth: true,
                                    bookType: 'xlsx'
                                });
                            });
                        }
                    });
                }).catch(() => {});
            },
            onWorkshopChange() {
                this.$set(this.searchParams, 'shiftId', null);
                this.$set(this.searchParams, 'groupId', null);
                this.getProcessListByWorkshop();
                // this.getShiftListRequest();
                this.getGroupListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getShiftListRequest() {
                return workforcemanagementShiftPage({
                    auditState: 1,
                    workshopId: this.searchParams.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                        this.$set(this.searchParams, 'shiftId', this.shiftList && this.shiftList.length ? this.shiftList[0].id : null);
                    }
                });
            },
            getGroupListRequest() {
                return personnelGroupPage({
                    workshopId: this.searchParams.workshopId,
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                const currentDate = formatDate(Date.now());
                this.$set(this.searchParams, 'belongDates', [currentDate, currentDate]);
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;

                this.getProcessListByWorkshop();
                this.tableLoading = true;
                await this.getGroupListRequest();
                // await this.getShiftListRequest();
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        resData.forEach(x => {
                            x.gramWeight = `${x.gramWeight}g/${x.meters}m`;
                        });
                        this.tableData = res.data.res || [];
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            }
        }
    };
</script>
<style>
</style>
